<?php
namespace App\Controller\App;

use App\Query\OrderQuery;
use App\Query\ConfigQuery;
use App\Query\UserAddressQuery;
use App\Query\UserQuery;
use App\Repository\ProductRepository;
use App\Repository\OrderRepository;

use App\Facade\Pay;
use App\Facade\Pays;

use App\Service\Code\CodeService;

class OrderController extends Controller
{
    // 创建订单
    public function index($id)
    {
        $user = $this->auth();
        
        // 配置
        $config = ConfigQuery::get();
        
        // 获取商品
        if(!$product = ProductRepository::find($id))
        {
            $this->error('error');
        }
        
        // 收货地址
        if(!$address = UserAddressQuery::user($user)->first())
        {
            $this->error('address');
        }
        
        // 校验金额
        [$total, $money, $money_make] = $this->check($config, $product->money, (float) $this->input('money_make'));
        
        // 扣掉余额
        if(!$user->makeMoney('money_make', $money_make, '购买【' . $product->name . '】'))
        {
            $this->error('money_make');
        }

        // 创建订单
        $order = OrderRepository::make();
        $res = $order->create($user, $product, [
            'name'    => $address->name,
            'phone'   => $address->phone,
            'data'    => $address->data,
            'address' => $address->address,
            'total'      => $total,
            'money'      => $money,
            'money_make' => $money_make,
        ]);
        
        if(!$res) $this->error('create');
        
        return ['id' => $order->id];
    }
    
    // 校验金额
    protected function check($config, $total, $money_make)
    {
        // 算出余额
        $money = bcsub($total, $money_make);
        
        // 判断不能超过 50%
        if(ConfigQuery::bi($config, 'order_money_make', $total) < $money_make)
        {
            $this->error('order_money_make');
        }
        
        return [$total, $money, $money_make];
    }
    
    // 获取订单
    protected function find($id)
    {
        // 获取订单
        if(!$order = OrderQuery::user($this->auth())->find($id))
        {
            $this->error('error');
        }
        
        return OrderRepository::make($order);
    }
    
    // 我的订单
    public function user()
    {
        return OrderQuery::query(
            OrderQuery::user($this->auth()),
            $this->inputs('status')
        )->paginate(10)->toArray();
    }
    
    // 关闭订单
    public function no($id)
    {
        $order = $this->find($id);
        
        // 状态
        if(!$order->setStatusNo())
        {
            $this->error('order_status');
        }
        
        $this->message('ok');
    }
    
    // 确认订单
    public function ok($id)
    {
        $order = $this->find($id);
        
        // 状态
        if(!$order->setStatusOk())
        {
            $this->error('order_status');
        }
        
        $this->message('ok');
    }
    
    // 银联支付订单
    public function unionpay($id)
    {
        $order = $this->find($id);
        
        // 状态
        if($order->statusPay())
        {
            $this->error('order_pay');
        }
        
         // 加载支付
        if(!$pay = Pay::run(strtolower($this->input('pay_type'))))
        {
            $this->error('pay_type');
        }

        $response = $pay->setMoney($order->payMoney())
                        ->setNotify(dirname($this->request->url()) . '/notify/' . $id)
                        ->send();

        if($response->error())
        {
            $this->error($response->message());
        }
        
        return $response->data();
    }
    
    // 银联回调
    public function unionpayNotify($id)
    {
        // 回调
        $notify = Pay::notify($this->request->all());
        
        // 不能出错
        if($notify->error())
        {
            return;
        }
        
        if($order = OrderRepository::find($id))
        {
            $order->setStatusPay('unionpay');
        }
        
        return $notify->response();
    }
    
    // 支付宝支付
    public function alipay($id)
    {
        $order = $this->find($id);
        
        // 状态
        if($order->statusPay())
        {
            $this->error('order_pay');
        }
        
        $response = Pays::alipay()->app()->service()
                        ->setMoney($order->payMoney())
                        ->setTitle($order->product_name)
                        ->setOrderId($order->id)
                        ->setNotify(dirname($this->request->url()) . '/notify/' . $id)
                        ->send();
        
        if(!$response)
        {
            $this->error('error');
        }
        
        return compact('response');
    }
    
    // 支付宝回调
    public function alipayNotify($id)
    {
        // 回调 
        $notify = Pays::alipay()->notify($this->request->all());
        
        // 不能出错
        if(!$notify || $notify->error())
        {
            return;
        }
        
        if($order = OrderRepository::find($id))
        {
            $order->setStatusPay('alipay');
        }
        
        return $notify->response();
    }
    
    // 余额支付
    public function money($id)
    {
        $user = $this->auth();
        
        $order = $this->find($id);
        
        // 状态
        if($order->statusPay())
        {
            $this->error('order_pay');
        }

        // // 验证验证码
        // if(!(new CodeService($user->phone))->check($this->input('code')))
        // {
        //     $this->error('code');
        // }
        
        // 扣掉余额
        if(!$user->makeMoney('money', $order->payMoney(), '支付【' . $order->product_name . '】'))
        {
            $this->error('money');
        }
        
        if($order->setStatusPay('money'))
        {
            $this->message('ok');
        }
        
        $this->error('error');
    }
    
    // 签到
    public function day()
    {
        $user = $this->auth();
        
        $config = ConfigQuery::get();
        
        // 检查团队业绩是否到了门槛
        if($user->money_user >= $config['order_day_money_user']) 
        {
            // 检查下级所有用户是否都到了门槛
            if(!UserQuery::moneyUserMin(UserQuery::user($user), $config['order_day_money_user'])->count())
            {
                // 关闭静态释放
                $user->setMoneyStatus();
            }
        }
        
        // 判断是否可释放静态
        if(!$user->getMoneyRemainTime())
        {
            $this->error('money_remain_time');
        }
        
        // 判断静态释放关闭
        if($user->moneyStatus())
        {
            $this->error('money_status');
        }
        
        // 获取需要释放的订单
        $orders = OrderQuery::remain(OrderQuery::user($this->auth()))->get();
        
        if($orders->isEmpty())
        {
            $this->error('day');
        }
        
        // 仓库
        $repository = OrderRepository::make();
        
        // 获取同等级下级用户
        $child = UserQuery::level(UserQuery::user($user), $user->level_id)->count();
        
        // 初始速度
        $speed = 100;
        
        // 记算加速度，不能超过最高
        $speed += min($child * $config['order_day_speed'], $config['order_day_speed_max']);
        
        // 释放的积分累计
        $total = 0;
        
        // 更新静态释放时间
        $user->setMoneyRemainTime();
        
        // 星期天跳过
        if(date('w') == 0)
        {
            $this->message('ok');
        }
        
        // 循环
        foreach($orders as $order)
        {
            $repository->model($order);
            
            // 获取释放积分
            $money = $repository->getMoneyRemain($config['order_day'], $speed);
            
            // 手动释放积分
            $money = $repository->makeMoneyRemain($money);
            
            // 加入
            $total = bcadd($total, $money, 2);
        }

        $user->orderMoneyRemainUser('day', $total, '每日签到');
        
        $this->message('ok');
    }
    
    // 统计未释放
    public function remain()
    {
        $money = OrderQuery::remain(OrderQuery::user($this->auth()))->sum('money_remain');
        
        return ['money' => (float) $money];
    }
}
